import axios from "axios";
import qs from "qs";
import { getToken } from "@/utils";
import { Toast } from "antd-mobile";
import { createBrowserHistory } from "umi";
const history = createBrowserHistory();
const request = axios.create({
  baseURL: "http://43.139.124.13:8888/",
  timeout: 8000,
});
// 添加拦截器

request.interceptors.request.use(
  function (config) {
    if (getToken()) {
      // 请求参数中添加token  ps实际都是在请求头中
      if (config.method === "get") {
        config.headers["token"] = getToken();
      }
      if (config.method === "post") {
        config.headers["token"] = getToken();
        // config.data.token = getToken();
      }
      if (config.method === "put") {
        config.headers["token"] = getToken();
        // config.data.token = getToken();
      }
      if (config.method === "delete") {
        config.headers["token"] = getToken();
        // config.data.token = getToken();
      }
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  function (res) {
    if (res.data.code === 2000) {
      // 登录状态过期或者未登录
      Toast.show({
        icon: "fail",
        content: "登录状态过期或未登录",
        afterClose: () => {
          // 清除登录相关缓存
          localStorage.removeItem("token");
          localStorage.removeItem("cartlength");
          //跳转到登录页  react直接跳转 页面不刷新 因此 需要 history.go(0) 刷新页面
          history.push("/login");
          history.go(0);
        },
      });
    }
    return res;
  },
  function (error) {
    return Promise.reject(error);
  }
);
export default request;
